import React, { useEffect, useState } from 'react'
import { Button, Descriptions, Dropdown, message, Modal, notification, Spin, Table, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  getProductPlanning,
  updatePlanStatus,
  importExceProductPlanning,
  exportExcelProductPlanning,
  getSpuDevDetailListByPlaningId,
} from '@/api/goods'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useViewStyleColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import { GOODS_PLAN_STATUS_OPTIONS } from '@/constant/goods'
import dayjs from 'dayjs'
import { type ITableData as ITableDataStyle } from '../Style/types'
import { downloadByUrl, exportNotification, getRecentThreeMonths, importNotification } from '@/utils/util'
import { UploadOutlined, ImportOutlined, PlusOutlined, DownOutlined } from '@ant-design/icons'
import { IMPORT_FILE_ENUM, STATUSNUM } from '@/constant'
import ImportFileModal from '@/components/ImportFileModal'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useGetClassIds from '@/hooks/useGetClassIds'
import useCachePage from '@/hooks/useCachePage'
export interface IOptionClass {
  value: string | number
  label: string
  children?: IOptionClass[]
  isLeaf?: boolean
}
const Index: React.FC = () => {
  const ProDevSeason = useGetProDevSeason()
  const SALESSEASON = useAppSelector((state) => state.login.DICTDATA.sales_season)
  const [viewInfo, setviewInfo] = useState<ITableData>({})
  const [viewList, setviewList] = useState<ITableDataStyle[]>([])
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormUpload] = useForm()
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [isModalShow, setIsModalShow] = useState<boolean>(false)
  const [isModalLoading, setisModalLoading] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const defaultDateRange = getRecentThreeMonths()
  const [spinning, setspinning] = useState<boolean>(false)
  const { classIdOptions, settinyClassIds, tinyClassIds, handleClassIdChange } = useGetClassIds()
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getProductPlanning, {
    form: form,
    defaultFieldsParams: {
      startTime: defaultDateRange,
      planStatus: 1,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        startTime: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        planStatus: 1,
      }
      setCachePage({
        ...paramsData,
      })
      search({
        ...paramsData,
      })
    } else {
      if (cacheData.tinyClassId && cacheData.tinyClassId.length > 0) {
        settinyClassIds(cacheData.tinyClassIds)
      }
      form.setFieldsValue({
        ...cacheData,
        startTime:
          cacheData.startTime && cacheData.endTime ? [dayjs(cacheData.startTime), dayjs(cacheData.endTime)] : null,
        tinyClassIds: cacheData.tinyClassId,
        planStatus: cacheData.planStatus != null ? cacheData.planStatus : null,
      })
      delete cacheData.tinyClassId
      search({
        ...cacheData,
        startTime: cacheData.startTime ? cacheData.startTime : null,
        endTime: cacheData.endTime ? cacheData.endTime : null,
        planStatus: cacheData.planStatus != null ? cacheData.planStatus : null,
      })
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    setviewInfo({})
  }
  const selectRows = (keys: React.Key[]) => {
    setselectKeys(keys)
  }
  const onShowStyleModal = (info: ITableData) => {
    getDetailById(info)
    setviewInfo(info)
    setIsModalShow(true)
  }

  const getDetailById = async (info: ITableData) => {
    setisModalLoading(true)
    const res = await getSpuDevDetailListByPlaningId<ITableDataStyle>({ planingId: info.planingId }).finally(() =>
      setisModalLoading(false),
    )
    console.log(res)
    if (res.code === 200) {
      setviewList(res.data)
    }
  }

  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }

  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await importExceProductPlanning<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const handleClickMore = async (info: any) => {
    if (info.key == STATUSNUM.CLOSE) {
      if (selectKeys.length === 0) {
        message.warning('请勾选需要取消企划的列表数据！')
        return
      }
      const res = await updatePlanStatus({ status: 0, planingIds: selectKeys })
      if (res.code === 200) {
        message.success('操作成功')
        search(params)
        setselectKeys([])
      }
      if (res?.code === 820000 && res?.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
          return <div key={item}>{item}</div>
        })
        notification.open({
          type: 'warning',
          message: res.msg,
          description: failInfo,
        })
      }
    }
  }

  return (
    <PageContainer className="goods_plan_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['planNo', 'designerName'], form)}
        searchConfig={[
          { label: '商品企划编号', name: 'planNo', type: 'Input', placeholder: '多个查询用英文逗号隔开' },
          { label: '开发季', name: 'seasonId', type: 'Select', option: ProDevSeason },
          { label: '创建时间', name: 'startTime', type: 'RangePicker', config: { showTime: true } },
          { label: '企划状态', name: 'planStatus', type: 'Select', option: GOODS_PLAN_STATUS_OPTIONS },
          {
            name: 'tinyClassIds',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          { label: '适销季节', name: 'seasonCode', type: 'Select', option: SALESSEASON },
          // { label: '设计师/买手', name: 'designerName', type: 'Input' },
        ]}
        onFinish={(vals: any) => {
          setselectKeys([])
          const paramsData = {
            ...vals,
            tinyClassIds: tinyClassIds.length > 0 ? tinyClassIds : null,
            startTime: vals?.startTime?.[0] && dayjs(vals.startTime[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: vals?.startTime?.[1] && dayjs(vals.startTime[1]).format('YYYY-MM-DD HH:mm:ss'),
          }
          search({
            ...paramsData,
          })
          setCachePage({
            ...paramsData,
            tinyClassId: vals.tinyClassIds,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectKeys([])
          settinyClassIds([])
          const paramsData = {
            current: 1,
            size: 10,
            startTime: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            planStatus: 1,
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="addPlan"
                type="primary"
                onClick={() => {
                  navigate('/goods/plan/add')
                }}
                icon={<PlusOutlined />}
              >
                新建商品企划
              </PermissionButton>
              <PermissionButton
                permission="batchAddPlan"
                onClick={() => {
                  setisUploadFileShow(true)
                }}
                icon={<ImportOutlined />}
              >
                批量新建商品企划
              </PermissionButton>
              {buttonCodeList.includes('offPlan') ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: [
                      {
                        key: STATUSNUM.CLOSE,
                        label: '取消企划',
                      },
                    ],
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportPlan"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectKeys.length > 0) {
                    paramsData.planIds = selectKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await exportExcelProductPlanning(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectKeys([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
        rowKey={(rows) => rows.planingId}
        columns={useIndexColumns({ onShowStyleModal, navigate })}
        {...tableProps}
        isScrollY
      />
      <Modal width={2000} title="查看开发款式" maskClosable open={isModalShow} onCancel={onCancel} footer={null}>
        <Descriptions
          layout="vertical"
          column={4}
          items={[
            {
              key: '1',
              label: '开发季',
              children: viewInfo?.devSeasonName || '-',
            },
            {
              key: '2',
              label: '商品企划编号',
              children: viewInfo?.planNo || '-',
            },
            {
              key: '3',
              label: '款式分类',
              children:
                (viewInfo.bigClassName ? viewInfo.bigClassName : '') +
                (viewInfo.midClassName ? '-' + viewInfo.midClassName : '') +
                (viewInfo.smallClassName ? '-' + viewInfo.smallClassName : '') +
                (viewInfo.tinyClassName ? '-' + viewInfo.tinyClassName : ''),
            },
            {
              key: '4',
              label: '适销季节',
              children: viewInfo?.seasonCodeName || '-',
            },
          ]}
        />
        <div className="header_table_style">
          <Table
            className="goods_special_table_wrap"
            bordered
            pagination={false}
            scroll={{
              x: 1000,
              y: 500,
            }}
            loading={isModalLoading}
            columns={useViewStyleColumns()}
            dataSource={viewList}
            rowKey={(rows) => rows.spuDevId}
            rowHoverable={false}
            rowClassName={(_, index) => {
              return index % 2 === 0 ? '' : 'zebra-row-odd'
            }}
          ></Table>
        </div>
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.GOODS_PLAN_IMPORT}
      ></ImportFileModal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
